package com.lfg.leetcode.leetcode0;

public class No75sortColors {

    public static void main(String[] args) {
        int[] array = new int[]{0, 2, 2};
        sortColors(array);
        for (int i : array) {
            System.out.println("[" + i + "]");
        }

    }

    public static void sortColors(int[] nums) {
        int i1 = 0;
        int i2 = 0;
        int i0 = 0;
        for(int i=0;i<nums.length;i++){
            if(nums[i] == 0){
                i0++;
            } else if(nums[i] == 1){
                i1++;
            }else if(nums[i] == 2){
                i2++;
            }
        }
        int i = 0;
        while(i0>0){
            nums[i++]=0;
            i0--;
        }   while(i1>0){
            nums[i++]=1;
            i1--;
        }   while(i2>0){
            nums[i++]=2;
            i2--;
        }
    }
    public static void sortColors2(int[] nums) {
        int index0 = 0;
        int index2 = nums.length - 1;
        for (int i = 0; i <= index2; ) {
            if (nums[i] == 2) {
                if (i != index2) {
                    swap(nums, i, index2);
                } else {
                    i++;
                }
                index2--;
            } else if (0 == nums[i]) {
                if (i != index0) {
                    swap(nums, i, index0);
                } else {
                    i++;
                }
                index0++;
            } else {
                i++;
            }
        }
    }

    public static void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
}

